package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Blog;
import dao.BlogDao;
import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: 33013
 * Date: 2023-11-08
 * Time: 20:47
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    ObjectMapper mapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String blogId = req.getParameter("blogId");
        if (blogId == null){
            HttpSession session = req.getSession(false);
            if(session == null){
                User user = new User();
                String json = mapper.writeValueAsString(user);
                resp.setContentType("application/json; charset=utf8");
                resp.getWriter().write(json);
                return;
            }
            User user = (User) session.getAttribute("user");
            if (user == null){
                user = new User();
                String json = mapper.writeValueAsString(user);
                resp.setContentType("application/json; charset=utf8");
                resp.getWriter().write(json);
                return;
            }
            String json = mapper.writeValueAsString(user);
            resp.setContentType("application/json; charset=utf8");
            resp.getWriter().write(json);
        }else {
            try {
                BlogDao dao = new BlogDao();
                Blog blog = dao.getblog(Integer.parseInt(blogId));
                if (blog == null){
                    User user = new User();
                    String json = mapper.writeValueAsString(user);
                    resp.setContentType("application/json; charset=utf8");
                    resp.getWriter().write(json);
                    return;
                }
                UserDao userDao = new UserDao();
                User user = userDao.serachByuserId(blog.getUserId());
                if(user == null){
                    user = new User();
                    String json = mapper.writeValueAsString(user);
                    resp.setContentType("application/json; charset=utf8");
                    resp.getWriter().write(json);
                    return;
                }
                String json = mapper.writeValueAsString(user);
                resp.setContentType("application/json; charset=utf8");
                resp.getWriter().write(json);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
